// pages/score/score.js
Page({
    data: {
        content: null,
        result: [],
        index: 0,
        flag: false,
        buttons: [{text: '确定'}],
        searchType: 'group'  // 默认搜索小组
    },

    // 切换搜索类型
    switchType() {
        this.setData({
            searchType: this.data.searchType === 'group' ? 'personal' : 'group',
            content: null,
            result: []
        });
    },

    getContent(e) {
        this.setData({
            content: e.detail.value
        });
    },

    goSearch() {
        if (!this.data.content) {
            wx.showToast({
                title: this.data.searchType === 'group' ? '请输入小组名称' : '请输入用户名',
                icon: 'none'
            });
            return;
        }

        if (this.data.searchType === 'group') {
            this.searchGroup();
        } else {
            this.searchPersonal();
        }
    },

    // 搜索小组成绩
    searchGroup() {
        var that = this;
        var database = wx.cloud.database();
        
        database.collection("group").where({
            groupname: that.data.content
        }).get().then((groupRes) => {
            if (groupRes.data.length === 0) {
                wx.showToast({
                    title: '未找到该小组',
                    icon: 'none'
                });
                that.setData({
                    result: []
                });
                return;
            }

            let zuyuan = groupRes.data[0].zuyuan || [];
            
            database.collection("finalScore").where({
                username: database.command.in(zuyuan)
            }).get().then((scoreRes) => {
                that.setData({
                    result: scoreRes.data
                });

                if (scoreRes.data.length === 0) {
                    wx.showToast({
                        title: '该小组暂无比赛成绩',
                        icon: 'none'
                    });
                }
            });
        });
    },

    // 搜索个人成绩
    searchPersonal() {
        var that = this;
        var database = wx.cloud.database();

        // 直接通过用户名查询成绩
        database.collection("finalScore").where({
            username: that.data.content
        }).get().then((scoreRes) => {
            that.setData({
                result: scoreRes.data
            });

            if (scoreRes.data.length === 0) {
                wx.showToast({
                    title: '该用户暂无比赛成绩',
                    icon: 'none'
                });
            }
        }).catch(err => {
            console.error("查询失败：", err);
            wx.showToast({
                title: '查询失败',
                icon: 'none'
            });
        });
    },

    tapback(e) {
        this.setData({
            index: e.currentTarget.id,
            flag: true
        });
    },

    mapmarker_choose() {
        this.setData({
            flag: false
        });
    }
});